# coding: Utf-8
import csv
import json
import sys
import uuid
from getopt import GetoptError, getopt
from os import getenv, popen, unlink
from os.path import exists
from sys import argv

import requests

tmp_dir_path = getenv("LOCALAPPDATA")


def get_uid():
    tmp_info_path = tmp_dir_path + "/slot_info_uuid"
    uid = ""
    if exists(tmp_info_path):
        file = open(tmp_info_path, "r", encoding="utf-8")
        uid = file.read()
        file.close()
    else:
        uid = uuid.uuid5(uuid.NAMESPACE_OID, "slot_info_uuid").hex
        file = open(tmp_info_path, "w", encoding="utf-8")
        file.write(uid)
        file.close()
    return uid


uid = get_uid()


def write_text(path, text):
    file = open(path, "w+", encoding="utf-8")
    file.write(text)
    file.close()
    pass


def write_wmic_csv(path, what):
    str = popen("wmic " + what + " get /format:csv").read().strip()
    while str.find("\n\n") >= 0:
        str = str.replace("\n\n", "\n")
    write_text(path, str)


def read_csv_2_json(path):
    ret = list()
    with open(path, encoding="utf-8") as f:
        reader = csv.reader(f)
        header = next(reader)
        for row in reader:
            ele = {"UID": uid}
            for index, cell in enumerate(row):
                ele[header[index]] = cell
            ret.append(ele)
    return ret


def main(argv):
    out_put = "./info.json"
    try:
        opts, _ = getopt(argv, "o:v", ["output", "help"])
    except GetoptError:
        return sys.exit(-1)
    for key, val in opts:
        if key in ("-h", "--help"):
            print("./main.py -o <url or path>")
            return sys.exit(0)
        elif key in ("-o", "--output"):
            out_put = val

    data = {"UID": uid}
    names = [
        "diskdrive",
        "csproduct",
        "memorychip",
        "cpu",
        "bios",
    ]
    for name in names:
        csv_path = tmp_dir_path + "/%s.csv" % name
        write_wmic_csv(csv_path, name)
        data[name] = read_csv_2_json(csv_path)
        unlink(csv_path)

    if out_put.startswith("https://") or out_put.startswith("https://"):
        try:
          r = requests.post(url=out_put, data=json.dumps(data))
        except Exception as err:
          print(err)
          sys.exit(-1)
        if r.status_code > 200 and r.status_code < 299:
            print(
                "try to post data to '%s', got status code %d"
                % (out_put, r.status_code)
            )
        sys.exit(-1)
    else:
        with open(out_put, "w+", encoding="utf-8") as file:
            file.write(
                json.dumps(
                    data,
                    indent=2,
                    ensure_ascii=False,
                )
            )
        sys.exit(0)


if __name__ == "__main__":
    main(argv[1:])
